'use strict';
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)


	const db = await  uniCloud.database();
		let result = await db.collection('myou-img-apis').where({status:true}).get()
		console.log(' result.data', result.data)
		let apiArrs = result.data || []
				
		let index = 0
		//如果返回的是一个数组的话，就之行遍历操作
		result.data instanceof Array  && getimage()
		
		
	
	 async function getimage () {
				let api =apiArrs[index].api
				const res = await uniCloud.httpclient.request(api,{
					method:"GET",
					contentType:"json",
					data:{},
					dataType:"json"
					
				})
				if(res.data.code == 200){
					console.log(">>>>Res",res.data.imgurl)
					 
					let pp = {
						category_name:apiArrs[index].name,
						image:res.data.imgurl,
						tags:apiArrs[index].name
					}
					db.collection("myou-imgs").add(pp).then(res=>{
						index++
						if(index < apiArrs.length){
							// getimage()
						}
						console.log('myou-imgs',res)
					})
				}
		}
		return result.data
	let api = "https://api.mtyqx.cn/tapi/random.php?return=json"
	const res = await uniCloud.httpclient.request(api,{
		method:"GET",
		contentType:"json",
		data:{},
		dataType:"json"
		
	})
	if(res.data.code == 200){
		console.log(">>>>Res",res.data.imgurl)
		let pp = {
			category_name:"动漫",
			image:res.data.imgurl,
			tags:"动漫",
			status:1
		}
		db.collection("myou-imgs").add(pp).then(res=>{
			console.log(res)
		})
	}
	// var result = (new Function("return"+res))()
	//返回数据给客户端
	return res
	
 
	
};
